import { defineStore } from "pinia";
import { ref } from "vue";
import { fetchDetailInfoAPI } from "@/api/detailAPI";
import type { DetailVO } from "@/types/detailType";
import type { Ref } from "vue";


const useDetailStore = defineStore("detailStore", () => {
   // 商品详情新鲜
   const detailInfo: Ref<DetailVO> = ref<DetailVO>({} as DetailVO);

   // 当前商品sku信息
   const localData = ref({});

   // 发送请求获取商品详情的回调函数
   const fetchDetailInfo = async (id: string) => {
      try {
         const { result }: { result: DetailVO } = await fetchDetailInfoAPI(id);
         detailInfo.value = result;
         localData.value = {
            _id: result.id,
            name: result.name,
            goods_thumb: result.mainPictures[0],
            spec_list: result.specs.map(item => ({
               name: item.name,
               list: item.values,
            })),
            sku_list: result.skus.map(item => ({
               _id: item.id,
               goods_id: detailInfo.value.id,
               goods_name: detailInfo.value.name,
               image: item.picture,
               price: item.price,
               stock: item.inventory,
               sku_name_arr: item.specs.map((item) => item.valueName),
            })),
         };
      } catch (error: any) {
         await error;
      }
   };

   return {
      detailInfo,
      localData,
      fetchDetailInfo,
   };
});

export default useDetailStore;